<?php

namespace app\api\controller;

use app\api\lib\Wechat;
use app\api\service\OrderService;
use app\common\model\activity\ActivityModel;
use app\common\model\activity\ActivityProductModel;
use app\common\model\NoticeModel;
use app\common\model\order\OrderModel;
use app\common\model\order\OrderRefundModel;
use app\common\model\user\UserActivityModel;
use think\facade\Db;
use EasyWeChat\Factory;

class Notify
{
    /**
     * 支付回调
     */
    public function pay()
    {
        $app = Factory::payment(Wechat::config()['config']);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $out_trade_no = $message['out_trade_no']; //支付回调订单号
            $transaction_id = $message['transaction_id']; //支付回调支付号
            $time_end = $message['time_end']; //支付回调支付时间
            $payment_time = strtotime($time_end);
            $total_fee = $message['total_fee']; //支付回调支付金额
            $payed = $total_fee / 100;
            $order = OrderModel::where('order_no', $out_trade_no)->find(); // 开始处理订单
            if (!$order || $order->pay_status == 1) return true; // 如果订单不存在 或者 订单已经支付过了 告诉微信，我已经处理完了，订单没找到，别再通知我了
            // 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                if (($message['result_code'] ?? null) === 'SUCCESS') { // 用户支付成功
                    OrderModel::where('id', $order['id'])->update([
                        'serial_number' => $transaction_id,
                        'payed' => $payed,
                        'can_refund_price' => $payed,
                        'payment_time' => $payment_time,
                        'pay_status' => 1,
                        'status' => 2,
                    ]);
                    if ($order['type'] == 0) {
                        OrderService::order_notice($order);
                        event('OrderDelivery', ['oid' => $order['id']]);
                    } else if ($order['type'] == 1) {
                        $ua = UserActivityModel::where('order_id', $order['id'])->field('quantity,activity_product_id')->find();
                        ActivityProductModel::where('id', $ua['activity_product_id'])
                            ->update(['stock' => new \think\db\Raw('stock-' . $ua['quantity'])]);
                        UserActivityModel::where('order_id', $order['id'])->update(['status' => 1]);
                        event('ActivityOrderDelivery', ['oid' => $order['id']]);
                    }
                } elseif (($message['result_code'] ?? null) === 'FAIL') {      // 用户支付失败
                    OrderModel::where('order_no', $out_trade_no)->update(['pay_status' => 0, 'status' => 1]);
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
        $response->send(); // return $response;
    }

    /**
     * 退款回调
     */
    public function refund()
    {
        $app = Factory::payment(Wechat::config()['config']);
        $response = $app->handleRefundedNotify(function ($message, $reqInfo, $fail) {
            // 其中 $message['req_info'] 获取到的是加密信息
            // $reqInfo 为 message['req_info'] 解密后的信息
            // $out_trade_no = $reqInfo['out_trade_no']; // 商户订单号
            // $success_time = $reqInfo['success_time']; // 退款时间
            $out_refund_no = $reqInfo['out_refund_no']; // 商户退款单号
            $orderRefund = OrderRefundModel::where('refund_no', $out_refund_no)->find();
            if (!$orderRefund) return true; // 如果订单不存在 告诉微信，我已经处理完了，订单没找到，别再通知我了
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                OrderRefundModel::where('refund_no', $out_refund_no)->update(['status' => 1, 'update_time' => time()]);
                $order = OrderModel::where('id', $orderRefund['order_id'])
                    ->field('id,order_no,user_id,can_refund_price,has_refund_price,type,status')->find();
                $can_refund_price = round($order['can_refund_price'] - $orderRefund['refund_price'], 2);
                $has_refund_price = round($order['has_refund_price'] + $orderRefund['refund_price'], 2);
                OrderModel::where('id', $orderRefund['order_id'])->update([
                    'can_refund_price' => $can_refund_price,
                    'has_refund_price' => $has_refund_price,
                    'pay_status' => $can_refund_price > 0 ? 3 : 4,
                    'status' => $can_refund_price > 0 ? $order['status'] : 0,
                    'update_time' => time()
                ]);
                if ($order['type'] == 0) {
                    $content = '订单"' . $order['order_no'] . '"退款已经处理完成，退款金额已原路返回，如遇任何问题请联系客服为您处理。';
                    (new NoticeModel())->send($order['user_id'], '系统通知', $content, 0, '', '', 3);
                    if ($can_refund_price <= 0) OrderService::return_card($order['id']);
                } else if ($order['type'] == 1) {
                    $userActivity = UserActivityModel::where('order_id', $order['id'])->find();
                    ActivityProductModel::where('id', $userActivity['activity_product_id'])
                        ->update(['stock' => new \think\db\Raw('stock+' . $userActivity['quantity'])]);

                      $refundReason = $can_refund_price > 0 ? '部分退款' : '退款';
                    $content = '<div style="font-size: 12px;">该笔活动门票系统已为您' . $refundReason . '，如遇任何问题请联系客服为您处理。</div>
                    <div style="display: flex;margin-top: 6px;">
                        <div style="background: #f5f5f5;padding: 6px;display: flex;align-items: center;border-radius: 4px;">
                            <img src="' . $userActivity['activity_img'] . '" style="width: 30px;height: 24px;object-fit: cover;display: block;border-radius: 2px;">
                            <div style="font-size: 12px;margin-left: 8px;">
                                ' . $userActivity['activity_name'] . '｜' . $userActivity['activity_product_name'] . '
                            </div>
                        </div>
                    </div>';
                    $url = '/pages/activity/index?type=1';
                    (new NoticeModel)->send($userActivity['user_id'], '活动通知', $content, 0, '', $url);
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
        $response->send();
    }
}
